package org.alex.samples.web;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;



@Controller
public class FileUploadController {
	
	@RequestMapping(value = "/toUpload",method=RequestMethod.GET)
	public String toUpload() {
		return "file/upload";
	}

	@RequestMapping(value = "/upload",method=RequestMethod.POST)
	public String upload(@RequestParam(value="file",required=false) MultipartFile file, HttpSession session,
			ModelMap model) {
		String path = session.getServletContext().getRealPath("upload"); // 获取上传到服务器上的文件路径
		String fileName = file.getOriginalFilename(); // 文件名称
		System.out.println(session.getServletContext());
		System.out.println(path);
		File targetFile = new File(path, fileName); 
		if (!targetFile.exists()) { // 判断此抽象路径名表示的文件或目录是否存在.
			targetFile.mkdirs(); // 建立多级文件夹
		}
		// 保存
		try {
			file.transferTo(targetFile); // 上传文件。
		} catch (IOException e) {
			e.printStackTrace();
		}
		model.addAttribute("message", "上传成功");
		return "result";
	}

}
